package com.jwm.power.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.zhxu.bs.MapSearcher;
import cn.zhxu.bs.SearchResult;
import cn.zhxu.bs.util.MapUtils;
import com.jwm.power.mapper.QueryMapper;
import com.jwm.power.model.entity.SysDics;
import com.jwm.power.model.entity.SysNotices;
import com.jwm.power.model.entity.XsfwCusarchive;
import com.jwm.power.model.entity.XsfwCussource;
import com.jwm.power.model.reponse.ResponseData;
import com.jwm.power.service.CustomeService;
import com.jwm.power.service.SysService;
import com.jwm.power.util.Ut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//  客户中心
@Controller
@RequestMapping("/cus")
public class CustomeController {

    @Autowired
    private CustomeService customeService;
    @Autowired
    private MapSearcher mapSearcher;              // 注入 BeanSearcher 的检索器
    @Autowired
    private QueryMapper queryMapper;

    //  获取客户档案数据
    @RequestMapping(value = "/queryCustomes", method = RequestMethod.GET)
    public void QueryCustomes(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 一行代码，实现一个用户检索接口（MapUtils.flat 只是收集前端的请求参数）
            String page = request.getParameter("cPage");
            String size = request.getParameter("pSize");
            String searchName = request.getParameter("searchName");
            Map<String, Object> params = MapUtils.builder()
                    .page(Integer.parseInt(page) - 1 , Integer.parseInt(size))                   // 偏移 0 条，查询 15 条（推荐写法）
                    .field("cusname", searchName).op("ct")
                    .build();
            Map<String, Object> dataMap = new HashMap<>();
            SearchResult<Map<String, Object>> searchResult = mapSearcher.search(XsfwCusarchive.class, params);
            dataMap.put("data", searchResult.getDataList());
            dataMap.put("totals", searchResult.getTotalCount());
            Ut.toJson(response, dataMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //  设置客户档案
    @RequestMapping(value = "saveCustomes", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData SaveCustomes(HttpServletRequest request, HttpServletResponse response) throws ParseException {
        return customeService.SaveCustomes(request);
    }

    //  获取客户来源数据
    @RequestMapping(value = "/queryCusSources", method = RequestMethod.GET)
    public void QueryCusSources(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 一行代码，实现一个用户检索接口（MapUtils.flat 只是收集前端的请求参数）
            String dicName = request.getParameter("sName");
            List<Map<String, Object>> searchResult = new ArrayList<>();
            if (dicName.length() > 0) {
                Map<String, Object> objectMap = new HashMap<>();
                objectMap.put("strCell", "distinct id, title, parentcode, code, orderbyid, datatype, is_last");
                objectMap.put("strChildCell", "c.id, c.title, c.parentcode, c.code, c.orderbyid, c.datatype, c.is_last");
                objectMap.put("strWhere", " title like '%" + dicName + "%'");
                objectMap.put("tName", " Xsfw_CusSource");
                objectMap.put("strChildWhere", " t.code = c.parentcode");
               searchResult = queryMapper.queryWithDatas(objectMap);
            } else {
                Map<String, Object> objectMap = MapUtils.flat(request.getParameterMap());
                objectMap.put("datatype", StpUtil.hasPermission("sources.type") ? 1 : 0);
               searchResult = mapSearcher.searchAll(XsfwCussource.class, objectMap);
            }
            Map<String, Object> dataMap = new HashMap<>();
            List<Map<String, Object>> treeMap = new ArrayList<>();
            //  重新组装树形数据
            for (Map<String, Object> objectMap : searchResult) {
                Integer isParent = 0;
                for (Map<String, Object> checkMap : searchResult) {
                    if (checkMap.get("code").equals(objectMap.get("parentcode"))) {
                        isParent = 1;
                    }
                }
                if(isParent == 0){
                    Map<String, Object> itemMap = Ut.loadTreeData(objectMap, searchResult,"code");
                    treeMap.add(itemMap);
                }
            }
            dataMap.put("data", treeMap);
            Ut.toJson(response, dataMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //  设置客户来源
    @RequestMapping(value = "saveCusSources", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData SaveCusSources(HttpServletRequest request, HttpServletResponse response) throws ParseException {
        return customeService.SaveCusSources(request);
    }
}
